package org.larkdoc.auth;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.larkdoc.model.entity.RoleInfo;
import org.larkdoc.model.entity.RoleRelPermissions;
import org.larkdoc.model.entity.UserInfo;
import org.larkdoc.service.RoleRelPermissionsService;
import org.larkdoc.service.RoleService;
import org.larkdoc.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * shiro 权限控制自定义Realm
 * 
 * @author  zhangpeijun[zhangpeijun1024@qq.com]
 * @version  [v1.0.1, 2017年10月17日]
 * @see  [相关类/方法]
 * @since  [产品/模块版本]
 */
public class UserShiroRealm extends AuthorizingRealm {
    
    private final static Logger LOG = LoggerFactory.getLogger(UserShiroRealm.class);
    
    @Autowired
    UserService                 userService;
    
    @Autowired
    RoleService                 roleService;
    
    @Autowired
    RoleRelPermissionsService   roleRelPermissionsService;
    
    /**
     * 权限配置
     * @param arg0
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
        LOG.info("加载权限配置");
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        String account = (String)arg0.getPrimaryPrincipal();
        // 获取角色
        List<RoleInfo> roles = roleService.selectByUserAccount(account);
        if (null != roles && !roles.isEmpty()) {
            for (RoleInfo roleInfo : roles) {
                // authorizationInfo.addRole(roleInfo.getName());
                authorizationInfo.addRole(roleInfo.getCode());
            }
        }
        // 配置URL 权限
        List<RoleRelPermissions> rrps = roleRelPermissionsService.selectByUserAccount(account);
        if (null != rrps && !rrps.isEmpty()) {
            String url;
            String urlPer;
            for (RoleRelPermissions rrp : rrps) {
                if (null == rrp || StringUtils.isBlank(rrp.getPerUrl())) {
                    continue;
                }
                url = rrp.getPerUrl();
                urlPer = rrp.getPermissions() == null ? "" : rrp.getPermissions();
                String[] pers = urlPer.split(",");
                if (null != pers && pers.length > 0) {
                    for (String per : pers) {
                        authorizationInfo.addStringPermission(url + "/" + per);
                    }
                }
            }
        }
        return authorizationInfo;
    }
    
    /**
     * 身份信息验证
     * @param arg0
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken arg0) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken)arg0;
        // 根据用户输入的帐号，获取DB的数据
        UserInfo userInfo = userService.getByAccount(token.getUsername());
        if (userInfo == null) {
            throw new UnknownAccountException();
        } else {
            // 传入DB中的数据，供subject中调用，进行对比。
            //return new SimpleAuthenticationInfo(userInfo.getName(), userInfo.getPassword(), getName());
            return new SimpleAuthenticationInfo(userInfo.getAccount(), userInfo.getPassword(), getName());
        }
    }
    
    @Override
    public String getName() {
        return getClass().getName();
    }
    
}
